import { useEffect, useState } from "react";
import Skeleton from "@/components/Skeleton";
import clsx from "clsx";
import styles from "./style.module.css";
type DataItemProps = {
  className?: string;
  value?: number;
  text?: string;
  onClick?: () => void;
};
const DataItem = (props: DataItemProps) => {
  const { value, text, onClick } = props;
  const [displayValue, setDisplayValue] = useState(0);

  useEffect(() => {
    // if (displayValue >= value) return

    // const timer = setInterval(() => {
    //     setDisplayValue((prev) => Math.ceil(prev + value / 20))
    // }, 1000/60)

    // return () => {
    //     clearInterval(timer)
    // }

    // fix bug 1220:NaN
    if (value === undefined || displayValue >= value) return;

    requestAnimationFrame(() => {
      setDisplayValue((prev) => Math.ceil(prev + value / 20));
    });
  }, [displayValue, value]);

  useEffect(() => {
    //  bug 1221:displayValue没有随着value的变化重置
    setDisplayValue(0);
  }, [value]);

  return (
    <div className={clsx("text-center flex flex-col", props.className)} onClick={onClick}>
      <Skeleton className={clsx("h-[56px]","leading-[56px]", styles.num)} loaded={!!value}>
        <p>{displayValue}</p>
      </Skeleton>
      <Skeleton className="h-[37px] leading-[37px]" loaded={!!text}>
        <p>{text}</p>
      </Skeleton>
    </div>
  );
};

export default DataItem;
